import { RouteProp, useNavigation, useRoute } from '@react-navigation/native';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
import { useCallback, useRef, useState, useEffect } from 'react';
import {
  StyleSheet,
  Text,
  View,
  TouchableOpacity,
  StatusBar,
  Animated,
  Dimensions,
  ActivityIndicator,
  Alert,
} from 'react-native';
import { useSafeAreaInsets } from 'react-native-safe-area-context';
import Share from 'react-native-share';
import { Video } from 'react-native-video';

import FastImage from '@d11/react-native-fast-image';
import IconDownload from '@svgs/icon_download.svg';
import IconBack from '@svgs/icon_header_back.svg';

import { BusinessAPI } from '@/api/reworkAPI';
import HeaderBar from '@/components/headerBar';
import { RootStackParamList } from '@/types/navigation';
import { pxToVh, pxToVw } from '@/utils/pxToVx';

const { width: SCREEN_WIDTH } = Dimensions.get('window');

// Use the same color palette from EnterText
const COLORS = {
  primary: '#2563EB',
  primaryLight: '#3B82F6',
  primaryDark: '#1E40AF',
  secondary: '#6366F1',
  accent: '#8B5CF6',
  background: '#FCFCFF',
  card: '#FFFFFF',
  text: '#1E293B',
  textLight: '#475569',
  textMuted: '#94A3B8',
  border: '#E2E8F0',
  borderLight: '#F1F5F9',
  shadow: 'rgba(0, 0, 20, 0.05)',
  gradient1: '#3B82F6',
  gradient2: '#2563EB',
  gradient3: '#1E40AF',
  gradientLight1: '#EFF6FF',
  gradientLight2: '#DBEAFE',
};

type PreviewExportRouteProp = RouteProp<RootStackParamList, 'PreviewExport'>;

const PreviewExport = () => {
  const insets = useSafeAreaInsets();
  const navigation = useNavigation<NativeStackNavigationProp<RootStackParamList>>();
  const route = useRoute<PreviewExportRouteProp>();
  const { videoUrl, message } = route.params;

  const [isPlaying, setIsPlaying] = useState(false);
  const [isBuffering, setIsBuffering] = useState(true);
  const [progress, setProgress] = useState(0);
  const [duration, setDuration] = useState(0);

  // Animation values for component entrance
  const fadeAnim = useRef(new Animated.Value(0)).current;
  const scaleAnim = useRef(new Animated.Value(0.97)).current;

  useEffect(() => {
    BusinessAPI.resultInfo({
      resultId: '123412341',
    }).then((res) => {});
  }, []);

  // Animate component mount
  useEffect(() => {
    // Fade and scale in the main screen
    Animated.parallel([
      Animated.timing(fadeAnim, {
        toValue: 1,
        duration: 400,
        useNativeDriver: true,
      }),
      Animated.timing(scaleAnim, {
        toValue: 1,
        duration: 400,
        useNativeDriver: true,
      }),
    ]).start();
  }, []);

  // Handle back navigation
  const handleBack = useCallback(() => {
    // Animate out before navigation
    Animated.parallel([
      Animated.timing(fadeAnim, {
        toValue: 0,
        duration: 200,
        useNativeDriver: true,
      }),
      Animated.timing(scaleAnim, {
        toValue: 0.97,
        duration: 200,
        useNativeDriver: true,
      }),
    ]).start(() => {
      navigation.goBack();
    });
  }, [navigation, fadeAnim, scaleAnim]);

  // Handle video playback
  const togglePlayback = useCallback(() => {
    setIsPlaying(!isPlaying);
  }, [isPlaying]);

  // Format time (seconds) to mm:ss
  const formatTime = (seconds: number) => {
    const minutes = Math.floor(seconds / 60);
    const remainingSeconds = Math.floor(seconds % 60);
    return `${minutes}:${remainingSeconds < 10 ? '0' : ''}${remainingSeconds}`;
  };

  // Handle export action
  const handleExport = useCallback(() => {
    // In a real app, this would trigger a download of the video
    console.log('Export video:', videoUrl);
    // Placeholder implementation - could be enhanced with actual file export
    Alert.alert('Success', 'Video has been exported');
  }, [videoUrl]);

  // Handle share action
  const handleShare = useCallback(() => {
    const shareOptions = {
      title: 'Share video',
      message: message,
      url: videoUrl,
    };

    Share.open(shareOptions)
      .then((res) => {
        console.log('Share response:', res);
      })
      .catch((err) => {
        console.log('Share error:', err);
      });
  }, [message, videoUrl]);

  return (
    <Animated.View
      style={[
        styles.container,
        {
          paddingTop: insets.top,
          opacity: fadeAnim,
          transform: [{ scale: scaleAnim }],
        },
      ]}
    >
      <StatusBar backgroundColor={COLORS.background} barStyle="dark-content" />

      {/* Header */}
      <HeaderBar title="Preview & Export" leftIcon={<IconBack />} onBack={handleBack} />

      {/* Video Player Container */}
      <View style={styles.videoContainer}>
        <Video
          source={{ uri: videoUrl }}
          style={styles.video}
          resizeMode="contain"
          paused={!isPlaying}
          onLoadStart={() => setIsBuffering(true)}
          onLoad={(data) => {
            setDuration(data.duration);
            setIsBuffering(false);
          }}
          onProgress={(data) => {
            setProgress(data.currentTime);
          }}
          onEnd={() => setIsPlaying(false)}
          repeat={false}
        />

        {/* Buffering indicator */}
        {isBuffering && (
          <View style={styles.bufferingContainer}>
            <ActivityIndicator size="large" color={COLORS.primary} />
          </View>
        )}

        {/* Video controls */}
        <View style={styles.videoControlsContainer}>
          <TouchableOpacity style={styles.playButton} onPress={togglePlayback}>
            {isPlaying ? (
              <View style={styles.pauseContainer}>
                <View style={styles.pauseBar} />
                <View style={styles.pauseBar} />
              </View>
            ) : (
              <View style={styles.playTriangle} />
            )}
          </TouchableOpacity>

          <View style={styles.progressBarContainer}>
            <View style={styles.progressBar}>
              <Animated.View style={[styles.progressFill, { width: `${(progress / duration) * 100}%` }]} />
            </View>
          </View>

          <Text style={styles.timeText}>{formatTime(progress)}</Text>
        </View>
      </View>

      {/* Message Display */}
      <View style={styles.messageContainer}>
        <FastImage source={require('@assets/logo.png')} style={styles.avatarImage} />
        <View style={styles.messageContent}>
          <View style={styles.messageHeader}>
            <Text style={styles.timestamp}>0:45 • Generated just now</Text>
          </View>
          <Text style={styles.messageText}>{message}</Text>
          <View style={styles.interactionBar}>
            <TouchableOpacity style={styles.interactionButton}>
              <Text style={styles.interactionButtonText}>Like</Text>
            </TouchableOpacity>
            <TouchableOpacity style={styles.interactionButton}>
              <Text style={styles.interactionButtonText}>Comment</Text>
            </TouchableOpacity>
          </View>
        </View>
      </View>

      {/* Footer Action Buttons */}
      <View style={styles.footerContainer}>
        <TouchableOpacity style={[styles.footerButton, styles.exportButton]} onPress={handleExport}>
          <IconDownload width={pxToVw(20)} height={pxToVw(20)} />
          <Text style={styles.exportButtonText}>Export</Text>
        </TouchableOpacity>

        <TouchableOpacity style={[styles.footerButton, styles.shareButton]} onPress={handleShare}>
          <Text style={styles.shareButtonText}>Share</Text>
        </TouchableOpacity>
      </View>
    </Animated.View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: COLORS.background,
  },
  videoContainer: {
    width: SCREEN_WIDTH,
    height: SCREEN_WIDTH * 0.75, // 4:3 aspect ratio
    backgroundColor: '#000',
    marginVertical: pxToVh(20),
    position: 'relative',
  },
  video: {
    width: '100%',
    height: '100%',
  },
  bufferingContainer: {
    ...StyleSheet.absoluteFillObject,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'rgba(0, 0, 0, 0.3)',
  },
  videoControlsContainer: {
    position: 'absolute',
    bottom: 0,
    left: 0,
    right: 0,
    height: pxToVh(44),
    backgroundColor: 'rgba(0, 0, 0, 0.5)',
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: pxToVw(10),
  },
  playButton: {
    width: pxToVw(30),
    height: pxToVw(30),
    borderRadius: pxToVw(15),
    backgroundColor: 'transparent',
    justifyContent: 'center',
    alignItems: 'center',
  },
  playTriangle: {
    width: 0,
    height: 0,
    backgroundColor: 'transparent',
    borderStyle: 'solid',
    borderLeftWidth: pxToVw(10),
    borderRightWidth: pxToVw(10),
    borderBottomWidth: pxToVw(15),
    borderLeftColor: 'transparent',
    borderRightColor: 'transparent',
    borderBottomColor: '#FFFFFF',
    transform: [{ rotate: '90deg' }],
    marginLeft: pxToVw(5),
  },
  pauseContainer: {
    flexDirection: 'row',
    width: pxToVw(14),
    justifyContent: 'space-between',
  },
  pauseBar: {
    width: pxToVw(4),
    height: pxToVw(16),
    backgroundColor: 'white',
    borderRadius: pxToVw(1),
  },
  progressBarContainer: {
    flex: 1,
    marginHorizontal: pxToVw(10),
  },
  progressBar: {
    height: pxToVh(4),
    backgroundColor: 'rgba(255, 255, 255, 0.3)',
    borderRadius: pxToVh(2),
  },
  progressFill: {
    height: '100%',
    backgroundColor: COLORS.primary,
    borderRadius: pxToVh(2),
  },
  timeText: {
    color: '#FFFFFF',
    fontSize: pxToVh(12),
    fontWeight: '500',
    marginLeft: pxToVw(10),
  },
  messageContainer: {
    marginHorizontal: pxToVw(20),
    flexDirection: 'row',
    backgroundColor: COLORS.card,
    borderRadius: pxToVw(12),
    padding: pxToVw(12),
    shadowColor: COLORS.shadow,
    shadowOffset: { width: 0, height: 2 },
    shadowOpacity: 0.1,
    shadowRadius: 4,
    elevation: 2,
  },
  avatarImage: {
    width: pxToVw(40),
    height: pxToVw(40),
    borderRadius: pxToVw(20),
    marginRight: pxToVw(12),
  },
  messageContent: {
    flex: 1,
  },
  messageHeader: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    marginBottom: pxToVh(4),
  },
  timestamp: {
    fontSize: pxToVh(12),
    color: COLORS.textMuted,
  },
  messageText: {
    fontSize: pxToVh(14),
    color: COLORS.text,
    marginBottom: pxToVh(8),
  },
  interactionBar: {
    flexDirection: 'row',
    marginTop: pxToVh(4),
  },
  interactionButton: {
    marginRight: pxToVw(16),
  },
  interactionButtonText: {
    fontSize: pxToVh(13),
    color: COLORS.textLight,
  },
  footerContainer: {
    flexDirection: 'row',
    paddingHorizontal: pxToVw(20),
    paddingBottom: pxToVh(20),
    marginTop: 'auto',
    marginBottom: pxToVh(10),
  },
  footerButton: {
    flex: 1,
    height: pxToVh(50),
    borderRadius: pxToVw(10),
    justifyContent: 'center',
    alignItems: 'center',
    flexDirection: 'row',
  },
  exportButton: {
    backgroundColor: COLORS.primary,
    marginRight: pxToVw(8),
  },
  shareButton: {
    backgroundColor: COLORS.background,
    borderWidth: 1,
    borderColor: COLORS.primary,
    marginLeft: pxToVw(8),
  },
  exportButtonText: {
    color: '#FFFFFF',
    fontSize: pxToVh(16),
    fontWeight: '600',
    marginLeft: pxToVw(8),
  },
  shareButtonText: {
    color: COLORS.primary,
    fontSize: pxToVh(16),
    fontWeight: '600',
  },
});

export default PreviewExport;
